<?php

namespace App\Http\Models;


class SpaceOrderDetail extends BaseMessage
{

    protected $table = 'tspaceorderdetail';
    protected $fillable = ['TODOID', 'TODSpaceID', 'TODBeginAt', 'TODEndAt', 'TODDate', 'TODPrice'];
    protected $guarded = ['TODID'];

    public static function isOrder($spaceId, $time, $datas)
    {
        $times = explode('-', $time);
        $times[0] .= ':59';
        $times[1] .= ':00';
        $temp = $times[0];
        $time[0] = str_replace("00", "59", $time[0]);
        foreach ($datas as $v) {
            if ($v->TODSpaceID == $spaceId && (($v->TODBeginAt <= $times[0] && $v->TODEndAt >= $times[1]) || ($v->TODBeginAt >= $temp && $v->TODEndAt > $times[1] && $v->TODBeginAt < $times[0]) || ($v->TODBeginAt < $temp && $v->TODEndAt <= $times[1] && $v->TODEndAt > $times[0]) || ($v->TODBeginAt >= $temp && $v->TODEndAt <= $times[1]))) {
                return false;
            }
        }
        return true;
    }

    public static function getDatas($date)
    {
        return self::where('TODDate', $date)->get();
    }

    public function doBasketballSave($data, $datas)
    {
        $SHalfID = Space::where('SID', $data['TODSpaceID'])->first()->SHalfID;
        $spaces = Space::where('SHalfID', $SHalfID)->take(2)->get();
        //var_dump($spaces->toArray());
        //var_dump($data);
        //die;
        $temp = array();
        foreach ($spaces as $v) {
            $temp['TODSpaceID'] = $v->SID;
            $temp['TODBeginAt'] = $data['TODBeginAt'];
            $temp['TODEndAt'] = $data['TODEndAt'];
            $temp['TODDate'] = $data['TODDate'];
            $temp['TODOID'] = $data['TODOID'];
            $temp['TODPrice'] = $data['TODPrice'] / 2;
            if (SpaceOrderDetail::isOrder($temp['TODSpaceID'], $data['TODBeginAt'] . '-' . $data['TODEndAt'], $datas)) {
                $this->doSave($temp);
            } else {
                return false;
            }

        }
        return true;
    }

    public static function isBasketballOrder($basketballIDs, $time, $datas)
    {
//        $SHalfID = Space::where('SID', $SHalfID)->first()->SHalfID;
//        $spaces = Space::where('SHalfID', $SHalfID)->take(2)->get();
        foreach ($basketballIDs as $v) {
            if (!self::isOrder($v, $time, $datas)) {
                return false;
            }
        }
        return true;
    }

}
